package gui;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.DefaultComboBoxModel;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import kalendar.calendar.JDateChooser;
import logic.Turno;
import util.InputHelper;

/**
 *
 * @author lucifer
 */
public class GenerarTurnosLibresDialog extends javax.swing.JDialog {

  public static final int RET_CANCEL = 0;
  public static final int RET_OK = 1;

  private int idMedico;
  private String medico;
  private LocalDate fechaDeUltimoTurno;

  public GenerarTurnosLibresDialog(java.awt.Frame parent, boolean modal, int id, String medicoNombreApellido, LocalDate fechaDeUltimoTurnoDelMedico) {
    super(parent, modal);
    initComponents();
    initComboBox();

    idMedico = id;
    medico = medicoNombreApellido;
    fechaDeUltimoTurno = fechaDeUltimoTurnoDelMedico;

    initWindow();
    initCal(desdejDateChooser);
    initCal(hastajDateChooser);

    desdejDateChooser.setDate(InputHelper.FromNewDateToOld(fechaDeUltimoTurno.atStartOfDay()));
    hastajDateChooser.setDate(InputHelper.FromNewDateToOld(fechaDeUltimoTurno.plusMonths(1).atStartOfDay()));

    String cancelName = "cancel";
    InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelName);
    ActionMap actionMap = getRootPane().getActionMap();
    actionMap.put(cancelName, new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        doClose(RET_CANCEL);
      }
    });
  }

  public int getReturnStatus() {
    return returnStatus;
  }

  private void initWindow() {
    String title = String.format("Habilitar turnos libres para el Dr. %s", medico);
    setTitle(title);

    String msg = String.format(
      "Dr. %s %s",
      medico,
      fechaDeUltimoTurno == null ? "no tiene turnos habilitados." : String.format("tiene turnos habilitados hasta el %s.", fechaDeUltimoTurno.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")))
    );

    fechaDeUltimoTurno = fechaDeUltimoTurno == null || fechaDeUltimoTurno.isBefore(LocalDate.now())? LocalDate.now() : fechaDeUltimoTurno.plusDays(1);

    turnosLibresParaElMedicojLabel1.setText(msg);
    turnosLibresAPartirDejLabel1.setText(
      String.format("Se pueden habilitar turnos a partir del %s.", fechaDeUltimoTurno.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")))
    );
  }

  private void initCal(JDateChooser cal) {
    cal.getJCalendar().getDayChooser().setDayBordersVisible(false);
    cal.getJCalendar().getDayChooser().setDecorationBackgroundVisible(false);
    cal.getJCalendar().getDayChooser().setDecorationBordersVisible(false);
    cal.getJCalendar().setDecorationBackgroundVisible(false);
    cal.getJCalendar().setDecorationBordersVisible(false);
    cal.setMinSelectableDate(InputHelper.FromNewDateToOld(fechaDeUltimoTurno.atStartOfDay()));
  }

  private void initComboBox() {
    String[] duraciones = {"10 minutos", "15 minutos", "20 minutos", "30 minutos"};
    intervalojComboBox.setModel(new DefaultComboBoxModel(duraciones));
    intervalojComboBox.setSelectedIndex(2);
  }

  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    okButton = new javax.swing.JButton();
    cancelButton = new javax.swing.JButton();
    turnosLibresParaElMedicojLabel1 = new javax.swing.JLabel();
    turnosLibresAPartirDejLabel1 = new javax.swing.JLabel();
    desdejPanel = new javax.swing.JPanel();
    desdejDateChooser = new kalendar.calendar.JDateChooser();
    hastajPanel = new javax.swing.JPanel();
    hastajDateChooser = new kalendar.calendar.JDateChooser();
    intervalojComboBox = new javax.swing.JComboBox();
    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent evt) {
        closeDialog(evt);
      }
    });

    okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/aceptar.png"))); // NOI18N
    okButton.setText("Aceptar");
    okButton.setMaximumSize(new java.awt.Dimension(120, 27));
    okButton.setMinimumSize(new java.awt.Dimension(120, 27));
    okButton.setPreferredSize(new java.awt.Dimension(120, 27));
    okButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        okButtonActionPerformed(evt);
      }
    });

    cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/cancelar.png"))); // NOI18N
    cancelButton.setText("Cancelar");
    cancelButton.setMaximumSize(new java.awt.Dimension(120, 27));
    cancelButton.setMinimumSize(new java.awt.Dimension(120, 27));
    cancelButton.setPreferredSize(new java.awt.Dimension(120, 27));
    cancelButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        cancelButtonActionPerformed(evt);
      }
    });

    turnosLibresParaElMedicojLabel1.setText("Médico");

    turnosLibresAPartirDejLabel1.setText("Fecha");

    desdejPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Desde el día", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP));

    desdejDateChooser.setDateFormatString("dd/MM/yyyy");

    javax.swing.GroupLayout desdejPanelLayout = new javax.swing.GroupLayout(desdejPanel);
    desdejPanel.setLayout(desdejPanelLayout);
    desdejPanelLayout.setHorizontalGroup(
      desdejPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, desdejPanelLayout.createSequentialGroup()
        .addContainerGap()
        .addComponent(desdejDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
        .addContainerGap())
    );
    desdejPanelLayout.setVerticalGroup(
      desdejPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(desdejPanelLayout.createSequentialGroup()
        .addContainerGap()
        .addComponent(desdejDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(12, 12, 12))
    );

    hastajPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Hasta el día", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP));

    hastajDateChooser.setDateFormatString("dd/MM/yyyy");

    javax.swing.GroupLayout hastajPanelLayout = new javax.swing.GroupLayout(hastajPanel);
    hastajPanel.setLayout(hastajPanelLayout);
    hastajPanelLayout.setHorizontalGroup(
      hastajPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, hastajPanelLayout.createSequentialGroup()
        .addContainerGap()
        .addComponent(hastajDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE)
        .addContainerGap())
    );
    hastajPanelLayout.setVerticalGroup(
      hastajPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(hastajPanelLayout.createSequentialGroup()
        .addContainerGap()
        .addComponent(hastajDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    jLabel1.setText("Duración de cada turno:");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGap(12, 12, 12)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
          .addGroup(layout.createSequentialGroup()
            .addGap(0, 0, Short.MAX_VALUE)
            .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
          .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
            .addGap(314, 314, 314)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(intervalojComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
          .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addComponent(turnosLibresParaElMedicojLabel1, javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(turnosLibresAPartirDejLabel1, javax.swing.GroupLayout.Alignment.LEADING)
              .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                .addComponent(desdejPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(hastajPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGap(0, 0, Short.MAX_VALUE)))
        .addGap(12, 12, 12))
    );

    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelButton, okButton});

    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
        .addGap(12, 12, 12)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(hastajPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
          .addComponent(desdejPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addGap(18, 18, 18)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(intervalojComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jLabel1))
        .addGap(18, 18, 18)
        .addComponent(turnosLibresParaElMedicojLabel1)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(turnosLibresAPartirDejLabel1)
        .addGap(18, 18, 18)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(12, 12, 12))
    );

    getRootPane().setDefaultButton(okButton);

    pack();
  }// </editor-fold>//GEN-END:initComponents

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
      int duracionDelTurnoEnMinutos = 20;

      switch (intervalojComboBox.getSelectedIndex()) {
      case 0:
        duracionDelTurnoEnMinutos = 10;
        break;
      case 1:
        duracionDelTurnoEnMinutos = 15;
        break;
      case 2:
        duracionDelTurnoEnMinutos = 20;
        break;
      case 3:
        duracionDelTurnoEnMinutos = 30;
        break;
      }

      final LocalDateTime desde = InputHelper.FromOldDateToNew(desdejDateChooser.getDate());
      final LocalDateTime hasta = InputHelper.FromOldDateToNew(hastajDateChooser.getDate());

      if (desde.isAfter(hasta)) {
        JOptionPane.showMessageDialog(this, "Rango de fechas incorrecto. La segunda fecha debe ser posterior a la primera.", "Atención!", JOptionPane.WARNING_MESSAGE);
        return;
      }

      final BarraProgreso barra = new BarraProgreso(this, true);

      final int duracion = duracionDelTurnoEnMinutos;
      new Thread(new Runnable() {
        @Override
        public void run() {
          try {
            Turno.GenerarTurnosLibres(idMedico, desde, hasta, duracion);
          } catch (SQLException e) {
            System.out.printf("?I'm really sick of exceptions\n");
          }
          barra.setVisible(false);
          barra.dispose();
          doClose(RET_OK);
        }
      }).start();

      barra.setVisible(true); // no cambiar el orden, aunque parezca que tiene que ir más arriba ;)
    }//GEN-LAST:event_okButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
      doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
      doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog
  
  private void doClose(int retStatus) {
    returnStatus = retStatus;
    setVisible(false);
    dispose();
  }

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton cancelButton;
  private kalendar.calendar.JDateChooser desdejDateChooser;
  private javax.swing.JPanel desdejPanel;
  private kalendar.calendar.JDateChooser hastajDateChooser;
  private javax.swing.JPanel hastajPanel;
  private javax.swing.JComboBox intervalojComboBox;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JButton okButton;
  private javax.swing.JLabel turnosLibresAPartirDejLabel1;
  private javax.swing.JLabel turnosLibresParaElMedicojLabel1;
  // End of variables declaration//GEN-END:variables

  private int returnStatus = RET_CANCEL;
}
